#include "SQLParser.h"
#include "parser/bison_parser.h"
#include "parser/flex_lexer.h"
#include <iostream>
#include <sstream>

namespace ment {

    // 静态成员初始化
    SQLParserConfig SQLParser::globalConfig_;
    std::unique_ptr<DefaultSQLParser> SQLParser::defaultInstance_;

    // ========== SQLParserContext 实现 ==========
    SQLParserContext::SQLParserContext() {
        reset();
    }

    SQLParserContext::~SQLParserContext() = default;

    void SQLParserContext::setConfig(const SQLParserConfig& config) {
        config_ = config;
    }

    //9.13
    std::vector<std::pair<std::string, std::pair<int, int>>> g_colPos;
    std::vector<std::pair<int, int>> g_valuePos;
    bool g_colPosMoved = false;

    // 静态成员初始化
    //SQLParserConfig SQLParser::globalConfig_;
    //std::unique_ptr<DefaultSQLParser> SQLParser::defaultInstance_;

    const SQLParserConfig& SQLParserContext::getConfig() const {
        return config_;
    }

    void SQLParserContext::reset() {
        errors_.clear();
    }

    void SQLParserContext::addError(const std::string& error, int line, int column) {
        std::stringstream ss;
        if (line >= 0 && column >= 0) {
            ss << "Line " << line << ", Column " << column << ": " << error;
        }
        else {
            ss << error;
        }
        errors_.push_back(ss.str());
    }

    const std::vector<std::string>& SQLParserContext::getErrors() const {
        return errors_;
    }

    // ========== SQLErrorHandler 实现 ==========
    SQLErrorHandler::SQLErrorHandler(SQLParserContext* context)
        : context_(context), hasErrors_(false) {
    }

    void SQLErrorHandler::handleError(const std::string& message, int line, int column) {
        hasErrors_ = true;
        if (context_) {
            context_->addError(message, line, column);
        }
        if (context_->getConfig().enableDebugMode) {
            std::cerr << "SQL Parser Error: " << message << std::endl;
        }
    }

    void SQLErrorHandler::handleWarning(const std::string& message) {
        if (context_ && context_->getConfig().enableDebugMode) {
            std::cerr << "SQL Parser Warning: " << message << std::endl;
        }
    }

    bool SQLErrorHandler::hasErrors() const {
        return hasErrors_;
    }

    void SQLErrorHandler::clearErrors() {
        hasErrors_ = false;
        if (context_) {
            context_->reset();
        }
    }

    // ========== SQLTokenizer 实现 ==========
    SQLTokenizer::SQLTokenizer(SQLParserContext* context)
        : context_(context) {
    }

    bool SQLTokenizer::tokenize(const std::string& sql, std::vector<int16_t>* tokens) {
        if (!initializeLexer(sql)) {
            return false;
        }

        yyscan_t scanner;
        if (ment_lex_init(&scanner)) {
            if (context_ && context_->getConfig().enableDebugMode) {
                std::cerr << "SQLTokenizer: Error when initializing lexer!" << std::endl;
            }
            return false;
        }

        YY_BUFFER_STATE state = ment__scan_string(sql.c_str(), scanner);
        YYSTYPE yylval;
        YYLTYPE yylloc;

        int16_t token = ment_lex(&yylval, &yylloc, scanner);
        while (token != 0) {
            tokens->push_back(token);
            token = ment_lex(&yylval, &yylloc, scanner);

            if (token == SQL_IDENTIFIER || token == SQL_STRING) {
                free(yylval.sval);
            }
        }

        ment__delete_buffer(state, scanner);
        ment_lex_destroy(scanner);
        cleanupLexer();
        return true;
    }

    bool SQLTokenizer::initializeLexer(const std::string& sql) {
        // 词法分析器初始化逻辑
        return !sql.empty();
    }

    void SQLTokenizer::cleanupLexer() {
        // 清理词法分析器资源
    }

    // ========== SQLSyntaxAnalyzer 实现 ==========
    SQLSyntaxAnalyzer::SQLSyntaxAnalyzer(SQLParserContext* context)
        : context_(context) {
    }

    bool SQLSyntaxAnalyzer::analyze(const std::string& sql, SQLParserResult* result) {
        return performSyntaxAnalysis(sql, result);
    }

    bool SQLSyntaxAnalyzer::performSyntaxAnalysis(const std::string& sql, SQLParserResult* result) {
        //9.13
        g_colPos.clear();
        g_valuePos.clear();
        g_colPosMoved = false;   // 重置标志


        yyscan_t scanner;
        YY_BUFFER_STATE state;

        if (ment_lex_init(&scanner)) {
            if (context_ && context_->getConfig().enableDebugMode) {
                std::cerr << "SQLSyntaxAnalyzer: Error when initializing lexer!" << std::endl;
            }
            return false;
        }


        state = ment__scan_string(sql.c_str(), scanner);

        int ret = ment_parse(result, scanner);
        bool success = (ret == 0);
        result->setIsValid(success);

        ment__delete_buffer(state, scanner);
        ment_lex_destroy(scanner);

        return success;
    }

    // ========== SQLParserFactory 实现 ==========
    SQLParserFactory& SQLParserFactory::getInstance() {
        static SQLParserFactory instance;
        return instance;
    }

    std::unique_ptr<ISQLParser> SQLParserFactory::createParser(const SQLParserConfig& config) {
        return std::make_unique<DefaultSQLParser>(config);
    }

    void SQLParserFactory::registerParserType(const std::string& type,
        std::function<std::unique_ptr<ISQLParser>()> factory) {
        factories_[type] = factory;
    }

    // ========== DefaultSQLParser 实现 ==========
    DefaultSQLParser::DefaultSQLParser(const SQLParserConfig& config) {
        context_ = std::make_unique<SQLParserContext>();
        context_->setConfig(config);
        errorHandler_ = std::make_unique<SQLErrorHandler>(context_.get());
        tokenizer_ = std::make_unique<SQLTokenizer>(context_.get());
        syntaxAnalyzer_ = std::make_unique<SQLSyntaxAnalyzer>(context_.get());
    }

    DefaultSQLParser::~DefaultSQLParser() = default;

    bool DefaultSQLParser::parse(const std::string& sql, SQLParserResult* result) {
        if (!result) {
            return false;
        }

        context_->reset();
        errorHandler_->clearErrors();

        bool success = syntaxAnalyzer_->analyze(sql, result);

        if (!success && context_->getConfig().enableDebugMode) {
            const auto& errors = context_->getErrors();
            for (const auto& error : errors) {
                std::cerr << "Parse Error: " << error << std::endl;
            }
        }

        return success;
    }

    bool DefaultSQLParser::tokenize(const std::string& sql, std::vector<int16_t>* tokens) {
        if (!tokens) {
            return false;
        }

        context_->reset();
        errorHandler_->clearErrors();

        return tokenizer_->tokenize(sql, tokens);
    }

    bool SQLParser::parse(const std::string& sql, SQLParserResult* result) {
        if (!defaultInstance_) {
            defaultInstance_ = std::make_unique<DefaultSQLParser>(globalConfig_);
        }
        return defaultInstance_->parse(sql, result);
    }

    bool SQLParser::tokenize(const std::string& sql, std::vector<int16_t>* tokens) {
        if (!defaultInstance_) {
            defaultInstance_ = std::make_unique<DefaultSQLParser>(globalConfig_);
        }
        return defaultInstance_->tokenize(sql, tokens);
    }

    std::unique_ptr<ISQLParser> SQLParser::createParser(const SQLParserConfig& config) {
        return SQLParserFactory::getInstance().createParser(config);
    }

    void SQLParser::setGlobalConfig(const SQLParserConfig& config) {
        globalConfig_ = config;
        defaultInstance_.reset(); // 重置默认实例以使用新配置
    }

    const SQLParserConfig& SQLParser::getGlobalConfig() {
        return globalConfig_;
    }

    // Private constructor to prevent instantiation.
    SQLParser::SQLParser() {
        if (globalConfig_.enableDebugMode) {
            std::cerr << "SQLParser: Use static methods or factory methods!" << std::endl;
        }
    }

} // namespace ment
